package hr.dario.fragments.app;

import hr.dario.fragments.R;
import hr.dario.fragments.data.DataBaseAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class LocationEdit extends Activity {

	private DataBaseAdapter mDbHelper;

	private EditText mNameText;
	private EditText mDescText;
	private Long mRowId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mDbHelper = new DataBaseAdapter(this);
		mDbHelper.open();

		setContentView(R.layout.location_edit);
		setTitle(R.string.edit_location);

		mNameText = (EditText) findViewById(R.id.loc_name);
		mDescText = (EditText) findViewById(R.id.loc_desc);

		Button confirmButton = (Button) findViewById(R.id.confirm);

		mRowId = (savedInstanceState == null) ? null
				: (Long) savedInstanceState
						.getSerializable(DataBaseAdapter.KEY_LOC_ID);

		populateFields();

		mDbHelper.close();
		confirmButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				setResult(RESULT_OK);
				finish();
			}
		});
	}

	private void populateFields() {
		if (mRowId != null) {
			mDbHelper.open();
			Cursor note = mDbHelper.fetchInput(
					DataBaseAdapter.DATABASE_TABLE_LOC, mRowId);
			startManagingCursor(note);
			mNameText.setText(note.getString(note
					.getColumnIndexOrThrow(DataBaseAdapter.KEY_LOC_NAME)));
			mDescText
					.setText(note.getString(note
							.getColumnIndexOrThrow(DataBaseAdapter.KEY_LOC_DESCRIPTION)));
			mDbHelper.close();
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		saveState();
		outState.putSerializable(DataBaseAdapter.KEY_LOC_ID, mRowId);
	}

	@Override
	protected void onPause() {
		super.onPause();
		saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
	}

	private void saveState() {
		String locName = mNameText.getText().toString();
		String locDesc = mDescText.getText().toString();
		mDbHelper.open();
		if (mRowId == null) {
			long id = mDbHelper.createInput(DataBaseAdapter.DATABASE_TABLE_LOC,
					locName, locDesc);
			if (id > 0) {
				mRowId = id;
			}
		} else {
			mDbHelper.updateInput(DataBaseAdapter.DATABASE_TABLE_LOC, mRowId,
					locName, locDesc);
		}
		mDbHelper.close();
	}

}
